#include <utils/DataCatcher.h>
#include <fstream>
#include <iomanip>

namespace myamg {
    DataCatcher& DataCatcher::instance() {
        static DataCatcher instance;
        return instance;
    }

    void DataCatcher::recordMatrix(const std::string &fileName, const int *rowPtr, const int *colIndex,
                             const double *values, const size_t nRows, const size_t nElements) {
        if (counter.find(fileName) == counter.end()) {
            counter[fileName] = 1;
        }
        std::ofstream file(fileName + "_" + std::to_string(counter[fileName]) + ".mtx");
        file << "%%MatrixMarket matrix coordinate real general\n";
        file << nRows << " " << nRows << " " << nElements << "\n";
        file << std::setprecision(16) << std::scientific;

        for (size_t i = 0; i < nRows; ++i) {
            for (int j = rowPtr[i]; j < rowPtr[i + 1]; ++j) {
                file << (i + 1) << " " << (colIndex[j] + 1) << " " << values[j] << "\n";
            }
        }
        counter[fileName] = counter[fileName] + 1;
    }

    void DataCatcher::recordVector(const std::string &fileName, const double *values, const size_t nElements) {
        if (counter.find(fileName) == counter.end()) {
            counter[fileName] = 1;
        }
        std::ofstream file(fileName + "_" + std::to_string(counter[fileName]) + ".mtx");
        file << "%%MatrixMarket matrix array real general\n";
        file << nElements << " 1\n";
        file << std::setprecision(16) << std::scientific;

        for (size_t i = 0; i < nElements; ++i) {
            file << values[i] << "\n";
        }
        counter[fileName] = counter[fileName] + 1;
    }
}
